package com.tju.resource.business.tb_purchase;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tju.resource.business.tb_app_log.TbAppLogService;
import com.tju.resource.common.ServiceException;
import com.tju.resource.mapper.*;
import com.tju.resource.model.*;
import com.tju.resource.result.Result;
import com.tju.resource.result.ResultEnum;
import com.tju.resource.result.ResultUtil;
import com.tju.resource.tool.tool.ClientParameters;
import com.tju.resource.tool.tool.EmptyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import static com.tju.resource.tool.tool.WeightParser.parse;
import static com.tju.resource.tool.tool.WeightParser.toUnit;

/**
 * 采购实现类
 */
@Service
public class TbPurchaseServiceImpl implements TbPurchaseService {

    @Autowired
    TbPurchaseMapper tbPurchaseMapper;
    @Autowired
    TbRmStoreMapper tbRmStoreMapper;
    @Autowired
    TbRawMatlMapper tbRawMatlMapper;
    @Autowired
    TbConsumablesMapper tbConsumablesMapper;
    @Autowired
    TbPurStoreMapper tbPurStoreMapper;
    @Autowired
    private TbAppLogService tbAppLogService;

    /**
     * 查询
     *
     * @param parameters
     * @return
     */
    @Override
    public Result<Object> get(ClientParameters parameters) {
        try {
            Page<TbPurchase> page = new Page<>(parameters.getPage(), parameters.getLimit());
            IPage<TbPurchase> iPage = tbPurchaseMapper.get(page, parameters);
            return ResultUtil.success(ResultEnum.SUCCESS, iPage.getRecords(), iPage.getTotal());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR);
    }

    /**
     * 添加
     *
     * @param tbPurchase
     * @return
     */
    @Transactional
    @Override
    public Result<Object> add(TbPurchase tbPurchase) {
        if (EmptyUtils.isEmpty(tbPurchase.getCoId()) && EmptyUtils.isEmpty(tbPurchase.getRmId()))
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, "耗材和原料必选一！");
        if (EmptyUtils.isNotEmpty(tbPurchase.getCoId()) && EmptyUtils.isNotEmpty(tbPurchase.getRmId()))
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, "耗材和原料二选一！");
        if(EmptyUtils.isNotEmpty(tbPurchase.getRmId())) {
            TbRawMatl rawMatl = tbRawMatlMapper.selectById(tbPurchase.getRmId());
            if (EmptyUtils.isEmpty(rawMatl)) return ResultUtil.error(ResultEnum.UNKONW_ERROR, "原料不存在");
            if(rawMatl.getRmType()==1){
                if(EmptyUtils.isEmpty(tbPurchase.getRmWeight()))
                    return ResultUtil.error(ResultEnum.UNKONW_ERROR, "原料重量不能为空");
                if(EmptyUtils.isEmpty(tbPurchase.getRmUnit()))
                    return ResultUtil.error(ResultEnum.UNKONW_ERROR, rawMatl.getRmName()+" 请选择重量单位");
                //转换单位
                Double rmWeight = parse(tbPurchase.getRmWeight(), toUnit(tbPurchase.getRmUnit()), toUnit(rawMatl.getRmUnit()));
                tbPurchase.setRmWeight(rmWeight); //赋值重量
                tbPurchase.setNeeds(null);  //数量为空
            }else {
                if (EmptyUtils.isEmpty(tbPurchase.getNeeds()) && tbPurchase.getNeeds() > 0)
                    return ResultUtil.error(ResultEnum.UNKONW_ERROR, "采购数量不可为空或不小于0！");
                tbPurchase.setRmWeight(null);  //重量为空
            }
            tbPurchase.setType(0);//原料
        }else {
            if (EmptyUtils.isEmpty(tbPurchase.getNeeds()) && tbPurchase.getNeeds() > 0)
                return ResultUtil.error(ResultEnum.UNKONW_ERROR, "采购数量不可为空或不小于0！");
            tbPurchase.setType(1);//耗材
            tbPurchase.setRmWeight(null);  //重量为空
        }
//        if (EmptyUtils.isEmpty(tbPurchase.getPrice()))
//            return ResultUtil.error(ResultEnum.UNKONW_ERROR, "采购单价不可为空！");
        //tbPurchase.setAmount(tbPurchase.getPrice() * tbPurchase.getNeeds());
        if (tbPurchaseMapper.insert(tbPurchase) > 0) {
            return ResultUtil.success(ResultEnum.SUCCESS, "添加成功！");
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR, "添加失败！");
    }

    /**
     * 删除
     *
     * @param tbPurchase
     * @return
     */
    @Override
    @Transactional
    public Result<Object> del(TbPurchase tbPurchase) {
        if (tbPurchaseMapper.deleteById(tbPurchase.getId()) > 0) {
            return ResultUtil.success(ResultEnum.SUCCESS, "删除成功！");
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR, "删除失败！");
    }

    /**
     * 修改
     *
     * @param tbPurchase
     * @return
     */
    @Override
    public Result<Object> upd(TbPurchase tbPurchase) {
        if (EmptyUtils.isEmpty(tbPurchase.getCoId()) && EmptyUtils.isEmpty(tbPurchase.getRmId()))
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, "耗材和原料必选一！");
        if (EmptyUtils.isNotEmpty(tbPurchase.getCoId()) && EmptyUtils.isNotEmpty(tbPurchase.getRmId()))
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, "耗材和原料二选一！");
//        if (EmptyUtils.isEmpty(tbPurchase.getNeeds()) && tbPurchase.getNeeds() > 0)
//            return ResultUtil.error(ResultEnum.UNKONW_ERROR, "采购数量不可为空或不小于0！");
//        if (EmptyUtils.isEmpty(tbPurchase.getPrice()))
//            return ResultUtil.error(ResultEnum.UNKONW_ERROR, "采购单价不可为空！");
//        tbPurchase.setAmount(tbPurchase.getPrice() * tbPurchase.getNeeds());
        if(EmptyUtils.isNotEmpty(tbPurchase.getRmId())) {
            TbRawMatl rawMatl = tbRawMatlMapper.selectById(tbPurchase.getRmId());
            if (EmptyUtils.isEmpty(rawMatl)) return ResultUtil.error(ResultEnum.UNKONW_ERROR, "原料不存在");
            if(rawMatl.getRmType()==1){
                if(EmptyUtils.isEmpty(tbPurchase.getRmWeight()))
                    return ResultUtil.error(ResultEnum.UNKONW_ERROR, "原料重量不能为空");
                if(EmptyUtils.isEmpty(tbPurchase.getRmUnit()))
                    return ResultUtil.error(ResultEnum.UNKONW_ERROR, rawMatl.getRmName()+" 请选择重量单位");
                //转换单位
                Double rmWeight = parse(tbPurchase.getRmWeight(), toUnit(tbPurchase.getRmUnit()), toUnit(rawMatl.getRmUnit()));
                tbPurchase.setRmWeight(rmWeight); //赋值重量
            }else {
                if (EmptyUtils.isEmpty(tbPurchase.getNeeds()) && tbPurchase.getNeeds() > 0)
                    return ResultUtil.error(ResultEnum.UNKONW_ERROR, "采购数量不可为空或不小于0！");
            }
        }else {
            if (EmptyUtils.isEmpty(tbPurchase.getNeeds()) && tbPurchase.getNeeds() > 0)
                return ResultUtil.error(ResultEnum.UNKONW_ERROR, "采购数量不可为空或不小于0！");
        }
        if (tbPurchaseMapper.updateById(tbPurchase) > 0) {
            return ResultUtil.success(ResultEnum.SUCCESS, "修改成功！");
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR, "修改失败！");
    }

    /**
     * 审核采购单
     *
     * @param tbPurchase
     * @return
     */
    @Transactional
    @Override
    public Result<Object> check(TbPurchase tbPurchase) {
        UpdateWrapper<TbPurchase> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", tbPurchase.getId());
        if (tbPurchase.getAppStatus() == 0) {
            updateWrapper.set("app_status", 1);
            boolean b = tbAppLogService.insertTbAppLog(new TbAppLog(4, tbPurchase.getId(), tbPurchase.getAppBy(), 1, tbPurchase.getRemark()));
            if (tbPurchaseMapper.update(null, updateWrapper) > 0 && b)
                return ResultUtil.success(ResultEnum.SUCCESS, "审核成功！");
        }
        throw new ServiceException("审核失败！");
    }

    @Override
    @Transactional
    public Result<Object> twoCheck(TbPurchase tbPurchase) {
        UpdateWrapper<TbPurchase> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", tbPurchase.getId());
        TbPurchase purchase = tbPurchaseMapper.selectById(tbPurchase.getId()); //查询
        if(EmptyUtils.isEmpty(purchase))
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, "不存在采购");
        if (tbPurchase.getAppStatus() == 1) {/*二次审核（采购回来的审核）*/
            updateWrapper.set("app_status", 2);
            boolean b = tbAppLogService.insertTbAppLog(new TbAppLog(4, tbPurchase.getId(), tbPurchase.getAppBy(), 1, tbPurchase.getRemark()));
            if (tbPurchaseMapper.update(null, updateWrapper) > 0&&b) {
                if (EmptyUtils.isNotEmpty(tbPurchase.getRmId())) {
                        TbRawMatl matl = tbRawMatlMapper.selectById(tbPurchase.getRmId());
                        if (EmptyUtils.isNotEmpty(matl)) {
                            UpdateWrapper<TbRawMatl> wrapper = new UpdateWrapper<>();
                            if(matl.getRmType() ==2) {
                                if(EmptyUtils.isEmpty(tbPurchase.getQuantity()))
                                    throw new ServiceException("采购数量不能为空");
                                if (tbPurchase.getQuantity() > tbPurchase.getNeeds())
                                    throw new ServiceException(String.format("审核数量：%s 不能大于采购数量：%s",tbPurchase.getQuantity(),tbPurchase.getNeeds()));
                                wrapper.set("rm_stoke", matl.getRmStoke() + tbPurchase.getQuantity());
                            } else if(matl.getRmType() ==1) {
                                if(EmptyUtils.isEmpty(tbPurchase.getWeight()))
                                    throw  new ServiceException("采购重量不能为空");
                                if (tbPurchase.getWeight() > purchase.getRmWeight())
                                    throw  new ServiceException(String.format("审核重量：%s 不能大于采购重量: %s",tbPurchase.getWeight(),purchase.getRmWeight()));
                                wrapper.set("rm_stoke", matl.getRmStoke() + tbPurchase.getWeight());
                            }
                            //添加录入记录
                            int insert = tbRmStoreMapper.insert(new TbRmStore(tbPurchase.getRmId(), tbPurchase.getQuantity(), tbPurchase.getAppBy(), tbPurchase.getSrcFrom(), EmptyUtils.isEmpty(tbPurchase.getRemark()) ? "无" : tbPurchase.getRemark(), tbPurchase.getAmount(), tbPurchase.getWeight()));
                            wrapper.eq("id", tbPurchase.getRmId());
                            if (tbRawMatlMapper.update(null, wrapper) > 0 &&insert>0)
                                return ResultUtil.success(ResultEnum.SUCCESS, "采购成功！");
                    }
                } else {
                        TbConsumables consumables = tbConsumablesMapper.selectById(tbPurchase.getCoId());
                        if (EmptyUtils.isNotEmpty(consumables)) {
                            if(EmptyUtils.isEmpty(tbPurchase.getQuantity()))
                                    throw new ServiceException("采购数量不能为空");
                            if (tbPurchase.getQuantity() > tbPurchase.getNeeds())
                            throw new ServiceException(String.format("审核数量：%s 不能大于采购数量：%s",tbPurchase.getQuantity(),tbPurchase.getNeeds()));
                            UpdateWrapper<TbConsumables> wrapper = new UpdateWrapper<>();
                            wrapper.eq("id", tbPurchase.getCoId());
                            wrapper.set("number", consumables.getNumber() + tbPurchase.getQuantity());

                            if (tbConsumablesMapper.update(null, wrapper) > 0 &&tbPurStoreMapper.insert(new TbPurStore(tbPurchase.getCoId(), tbPurchase.getQuantity(), tbPurchase.getAmount(), EmptyUtils.isEmpty(tbPurchase.getRemark()) ? "无" : tbPurchase.getRemark(), tbPurchase.getAppBy()))>0) {
                                return ResultUtil.success(ResultEnum.SUCCESS, "采购成功！");
                            }
                        }
                }
            }
        }
        throw new ServiceException("审核失败！");
    }
}
